package com.base.common;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.Random;

/**
 * @Title  请求工具类
 * @Author 覃忠君 on 2016/10/26.
 * @Copyright © 长笛龙吟
 */
public class RequestContextUtils {

    public static boolean isAjaxRequest(HttpServletRequest request){
        String requested_with = request.getHeader("x-requested-with");
        if("XMLHttpRequest".equalsIgnoreCase(requested_with)){
            return true;
        }
        return false;
    }

    /**
     * 获取请求头 referer
     * @param request
     * @return
     */
    public static String getReferer(HttpServletRequest request){
        String referer = request.getHeader("referer");
        return referer;
    }

    /**
     * 判断服务器是否是本地（即开发环境）; 根据配置文件决定
     *
     * @return 如果服务器是本地，则返回 true
     */
    public static boolean isLocalhost(HttpServletRequest request) {
        String host = request.getRemoteAddr();
        if("localhost".equals(host) || "127.0.0.1".equals(host)){
            return true;
        }
        return false;
    }

    /**
     * 获取网站请求绝对路径
     *
     * @return 根路径
     */
    public static String getAbsoluteRequestPath(HttpServletRequest request) {
        if (isLocalhost(request)) {
            return request.getScheme() + "://" + request.getServerName() + ":"
                    + request.getServerPort() + request.getContextPath();
        }
        return request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort() + request.getContextPath();
    }

    /**
     * 获取访问设备
     * @param request
     * @return
     */
    public static AccessSite getAccessDevice(HttpServletRequest request){
        String useAgent = request.getHeader("user-agent");
        String deviceName = "unkown";
        if(StringUtils.isBlank(useAgent)){ // unkown device
            return new AccessSite(false, deviceName);
        }

        //Windows 桌面系统
        if (useAgent.contains("Windows NT")) {
            return new AccessSite(false, "Windows");  // PC windows
        }else if (useAgent.contains("Macintosh") && useAgent.contains("Mac OS")) {//苹果桌面系统
            return new AccessSite(false, "MacOS");   // PC Mac
        }else if(useAgent.contains("Ubuntu")){//Ubuntu系统
            return new AccessSite(false, "Ubuntu"); //PC Ubuntu
        }

        for (String item : AccessSite.mobile_type) {
            if (useAgent.contains(item)) {
                return new AccessSite(true, "MQQBrowser".equals(item) ? "weixin" : item);
            }
        }
        return new AccessSite(false, deviceName);// unkown device
    }


    /**
     * 添加参数到Url上
     * @param url
     * @param repeat 是否允许出现重复参数  true 允许重复  false 不允许
     * @param params   key1=value1, key2=value2, ...
     * @return
     */
    public static String  addParamsToUrl(String url, boolean repeat, String ... params){
        StringBuilder sb = new StringBuilder(url);
        if(params != null){
            for(int i = 0; i < params.length; i++){
                if(!repeat && sb.indexOf(params[i]) != -1){
                    continue;
                }
                if(i == 0){
                    if(url.contains("?")){
                        sb.append("&");
                    }else {
                        sb.append("?");
                    }
                }else {
                    sb.append("&");
                }
                sb.append(params[i]);
            }
        }
        return sb.toString();
    }

    public static String  addParamsToUrl(String url, String ... params){
        return addParamsToUrl(url,false,params);
    }

    /**
     * 获取客户端ip地址
     *
     * @param request
     * @return
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 多个路由时，取第一个非unknown的ip
        final String[] arr = ip.split(",");
        for (final String str : arr) {
            if (!"unknown".equalsIgnoreCase(str)) {
                ip = str;
                break;
            }
        }
        return ip;
    }

    /**
     * 根据cookie名称获取 cookie值
     * @param name
     * @param request
     * @return
     */
    public static String  getCookieByName(String name, HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies == null || cookies.length == 0){
            return BaseConstants.EMPTY_STRING;
        }

        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            String nameCookie = cookie.getName();
            if(nameCookie.equals(name)){
                return cookie.getValue();
            }
        }
        return BaseConstants.EMPTY_STRING;
    }
}